const fs = require('fs');
const path = require('path');
const readlineSync = require('readline-sync');

// 找到指定文件夹，如没有该路径则递归创建路径目录
function createDirIfNotExists(dirPath) {
    if (!fs.existsSync(dirPath)) {
        createDirIfNotExists(path.dirname(dirPath));
        fs.mkdirSync(dirPath);
    }
}

// 在指定的目录下，创建指定文件，并向文件中写入动态生成的代码
function createFileWithCode(filePath, code) {
    createDirIfNotExists(path.dirname(filePath));
    fs.writeFileSync(filePath, code);
}

// 获取指定目录下的js文件，并在指定js文件中识别特定的string代码串，并在代码串后添加指定动态生成的代码，并写回文件
function appendCodeToFile(filePath, searchString, code) {
    const fileContent = fs.readFileSync(filePath, 'utf8');
    const index = fileContent.indexOf(searchString);
    if (index !== -1) {
        const newContent = fileContent.slice(0, index + searchString.length) + '\n' + code + '\n' + fileContent.slice(index + searchString.length);
        fs.writeFileSync(filePath, newContent);
    }
}


// 读取文件\在最后一行添加代码
function appendCodeToFileEnd(filePath, code, callback) {
    // 读取文件
    fs.readFile(filePath, 'utf8', (err, data) => {
        if (err) return callback(err);

        // 在最后一行添加代码
        const newData = data + '\n' + code;

        // 写入文件
        fs.writeFile(filePath, newData, 'utf8', (err) => {
            if (err) return callback(err);
            if(callback) callback(null);
        });
    });
}

// 示例用法
// const dirPath = './control';
// const filePath1 = './test/index1.js';
// const filePath2 = './test/index2.js';
// const code = 'console.log("Hello, world!");';
// const searchString = 'console.log("Hello, ChatGPT!");';
// const dynamicCode = 'console.log("This code is dynamically generated!");';
//
// createDirIfNotExists(dirPath);
// createFileWithCode(filePath1, code);
// appendCodeToFile(filePath2, searchString, dynamicCode);


const projName = 'build_test_proj'
const projChName = '新建活动'
const otherPages = ['build_schedule_test_proj'] //除了index的目录

const answer = readlineSync.question('请确认已经添加指定的表示string（yes?）：');
if (answer === 'yes') {
    console.log('代码执行中...');
    // 在这里编写需要执行的代码
} else {
    console.log('输入不正确，程序已退出。');
}


//1、在controllers中创建name.py，内容是
let controllerPath = `./controllers/${projName}.py`
let controllerStr =
`from copy import deepcopy

import past
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

${projName}_api = Blueprint('${projName}_api', __name__) 

@${projName}_api.route('/${projName}_action', methods=['GET', 'POST'])
def @${projName}_action():
    pass
`
createFileWithCode(controllerPath, controllerStr);

//2、db数据库中添加相应的模块
// 将字符串转换成驼峰模式
let dbDir = './controllers/db.py'
const dbCaseStr = projName.replace(/_([a-z])/g, (match, p1) => p1.toUpperCase()).replace(/^\w/, (match) => match.toUpperCase());
console.log('db_CaseStr:',dbCaseStr); // 输出 "MyStringIsInUnderscoreFormat"
let dbStr =
`
class ${dbCaseStr}(db.Model):
    __tablename__ = "${projName}"
    id = db.Column(db.Text, primary_key=True, unique=True)  # id 整型，主键，自增，唯一
    remark = db.Column(db.String)

    def to_dict(self):
        pass
`
appendCodeToFileEnd(dbDir,dbStr)


//3、app中使用
let appDir = './app.py'

// + 在app中导入蓝图
let importStr =
`
from controllers.${projName} import (
    ${projName}_api
)
`
appendCodeToFile(appDir,'ly_import_blueprint',importStr)

// + 在app中注册蓝图
let registerStr =
`
app.register_blueprint(${projName}_api, url_prefix='/')
`
appendCodeToFile(appDir,'ly_register_blueprint',registerStr)


//3、前端src创建文件夹
let srcChildDir = `./src/${projName}`
createDirIfNotExists(srcChildDir)

//4、创建文件
let indexDir = `./src/${projName}/index.vue`
let indexStr =
`
<template>
    <div>请开始你的表演</div>
</template>
`
createFileWithCode(indexDir,indexStr)

//5
//+ router中添加你的module
// let srcModuleFile = `./src/module/${projName}.js`
// let moduleStr =
// `export const ${projName}_router = {
//   path: '/${projName}/index',
//   component: () => import('@/${projName}/index.vue')
// };
// `
// createFileWithCode(srcModuleFile,moduleStr)

//+ router/index中添加你的index路径
let routerDir = `./src/router/index.js`
let routerStr =
`      {
        path: '/${projName}/index',
        component: () => import('../${projName}/index.vue'),
      },
`
appendCodeToFile(routerDir,'ly-router-index',routerStr)

//6 common中添加你的sider bar路径
let sideDir = `./src/common/sidebar.vue`
let sideStr =
`          {
              icon: 'el-icon-setting',
              index: '/${projName}/index',
              title: '${projChName}'
            },
`
appendCodeToFile(sideDir,'ly-sidebar',sideStr)

